package filter;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;

public class IsLoginFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        // 获得cookie
        Cookie[] cookies = req.getCookies();
        System.out.println("过滤"+req.getServletPath());
        if (session.getAttribute("username") != null) {
            if (session.getAttribute("username").toString().equals("admin") && session.getAttribute("password").toString().equals("123456")) {
                System.out.println("已登录");
                if(req.getServletPath().contains("login.jsp")){
                    request.getRequestDispatcher("success.jsp").forward(request, response);
                    return;
                }
            }
        }else if (findCookie(cookies, "autoLogin")) {
            System.out.println("自动登录，从cookie中获取用户名和密码");
            if (findCookie(cookies, "username")) {
                String username = getCookieValue(cookies, "username");
                String password = getCookieValue(cookies, "password");
                session.setAttribute("username", username);
                session.setAttribute("password", password);
            }
        } else {
            System.out.println("拦截所有页面没有登录,则跳至登录页面");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

        chain.doFilter(request, response);
    }

    public void destroy() {
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }

    public boolean findCookie(Cookie[] cookies, String cookieName) {
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookieName.equals(cookie.getName())) {
                    return true;
                }
            }
        }
        return false;
    }

    public String getCookieValue(Cookie[] cookies, String cookieName) {
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookieName.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return "";
    }

}
